var pageObj1={type:"1-120",width:[245],height:[0,0,50]};
var layoutContainer1 = create_layout(pageObj1);
var hosToolbar,selectedHosToolbar;
var hosGrid, selectedHosGrid;
var randomNum = getRandomNum();
var arrayList = new Array();
var isChange = false;

$(function(){
    hosToolbar = layoutContainer1.layout.items[0].attachToolbar({});
    hosToolbar.setIconsPath(basePP + "images/main/button/toolbar/");
    hosToolbar.addInput("searchKey",3,"输入医院名",100);
    hosToolbar.addButton("search", 4, "查询", "viewStock.png", "");
    hosToolbar.setAlign("right");
    hosToolbar.attachEvent("onClick", doOnClickRoleTool);

    selectedHosToolbar = layoutContainer1.layout.items[1].attachToolbar({});
    selectedHosToolbar.setIconsPath(basePP + "images/main/button/toolbar/");
    selectedHosToolbar.addText("label",2,"授权医院：",100);
    initSelectedHosGrid();
    initHosGrid();
    searchHosSelected();
    searchHos();
    //增加搜索键盘事件
    hosToolbar.attachEvent("onEnter", function(id, value){
        searchHos();
    });
    //----------------------------------------------------------------!!!样式!!!
    $('.inp').focus(function(){	this.value='';}); //获取焦点后置空输入框
    layoutContainer1.layout.items[0].fixSize(true, false);//固定布局尺寸
    $('.dhtmlxLayoutPolySplitterVerInactive div').css("width","3px");//分割线
});

//初始化医院列表
function initHosGrid() {
    hosGrid = layoutContainer1.grid[0];
    dmjplugs.grid.createGrid({
        sm:'ch',
        skin:'dhx_skyblue',
        srcc:true,
        validate : true,
        columns:[
            {header:'id',id:'id',width:10,hidden:true},
            {header:'hosCode',id:'hos_code',width:10,hidden:true},
            {header:'areaCode',id:'area_code',width:10,hidden:true},
            {header:'医院',id:'hos_name',width:'*'},
            {header:'dataStatus',id:'data_status',width:'*',hidden:true}
        ]
    },hosGrid);
    hosGrid.setTotal(0);
    hosGrid.enableMultiselect(true);
    hosGrid.enableMultiline(true);
    hosGrid.enableEditEvents(false,false,false);
    // hosGrid.setColumnHidden(0,true);
    hosGrid.attachEvent("onRowSelect",function(rId) {
        onSelectHosRow(rId);
    });
    hosGrid.attachEvent("onCheck",function(rId,cInd,state){

        if(state){
            //行选中
            // hosGrid.selectRow(hosGrid.getRowIndex(rId),true,true,true);
        } else {
            //取消行选中
            hosGrid.clearSelection();
            for (var i=0; i<arrayList.length; i++) {
                if (rId == arrayList[i]){
                    arrayList.splice(i,1);
                    break;
                }
            }
            for (var j=0;j<arrayList.length;j++) {
                hosGrid.selectRow(hosGrid.getRowIndex(arrayList[j]),true,true,true);
            }
            // reSelect();
        }
    });
}

function reSelect() {
    var checked = hosGrid.getCheckedRows(0);
    if (checked != null) {
        var array = new Array(); //定义一数组
        array = checked.split(",");
        for (var i=0;i<array.length;i++) {
            hosGrid.selectRow(hosGrid.getRowIndex(array[i]),true,true,true);
        }
    }
}

//初始化授权医院列表
function initSelectedHosGrid() {
    selectedHosGrid = layoutContainer1.grid[1];
    dmjplugs.grid.createGrid({
        sm:'ch',
        skin:'dhx_skyblue',
        srcc:true,
        validate : true,
        columns:[
            {header:'id',id:'id',width:10,hidden:true},
            {header:'医院',id:'hos_name',width:'*'},
        ]
    },selectedHosGrid);
    selectedHosGrid.setTotal(0);
    selectedHosGrid.enableEditEvents(false,false,false);
    selectedHosGrid.setColumnHidden(0,true);
}

//初始化form1
function doOnFormInit1(){
    //按钮事件
    if (typeof(editForm1) == "object"){
        editForm1.attachEvent("onButtonClick", function(name, command) {
            switch(command) {
                case 'save':doSave();break;
                case 'cancle':doCancle();break;
            }
        });
    }
}

//保存数据授权信息
function doSave(){
    var hoss = getCheckedRowsByGrid(hosGrid, hosGrid.getColIndexById('select'));
    if (hoss == null || hoss.length == 0) {
        $func.alert("请先选择医院，再分配权限！", "red");
        return;
    }
    var list = new Array();
    for (var i=0;i<hoss.length;i++) {
        list.push(hoss[i].hos_code);
    }
    $.ajax({
        url: basePath+'managerAlipayUser/saveAlipayUserHos/'+parent.oneAdminInfo.alipay_id,
        type: 'post',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(list),
        success: function (back) {
            if(!back||!back.result){
                $func.alert(back.message?back.message:"保存失败", "red");
                return;
            }
            $func.alert("保存成功！", "green");
            doCancle();
        }
    });
}

//取消
function doCancle(){
    parent.authorityWin.close();
}

function doOnClickRoleTool(id){
    switch (id) {
        case 'search':searchHos();break;
    }
}

//查询医院列表
function searchHos(vContent){//加载医院数据 ,先索引后数据库
    var searchType=1; //search_Form.getItemValue("docSearchType") ;
    var searchKey=hosToolbar.getValue("searchKey"); //search_Form.getItemValue("docSearchKey") ;
    if(vContent) searchKey=vContent;
    if(searchKey=='输入医院名') searchKey='';
    hosGrid.setTotal(0);
    hosGrid.clearAll();
    var postData="pageNo=1&pageSize=200&pageCount=0";
    if(searchKey&&searchKey.length>0){
        postData+="&hosName="+searchKey;
    }
    $.ajax({
        url: basePath+'hospital/findAllParentHospitalGrid',
        type: 'post',
        dataType: 'json',
        data:encodeURI(postData),
        success: function(back, textStatus, jqXHR) {
            if(!back){
                $func.alert("请求失败,状态:"+textStatus);
                return;
            }
            if(back.rowCount>0){
                hosGrid.parse(back.gridr, "json");
                hosGrid.setTotal(back.rowCount);
                hosGrid.uncheckAll();

                var hoss = getCheckedRowsByGrid(selectedHosGrid, selectedHosGrid.getColIndexById('select'));
                if (hoss != null) {
                    hosGrid.forEachRow(function (id) {
                        var idd = $.trim(hosGrid.cells(id, hosGrid.getColIndexById('id')).getValue());
                        var flag = false;
                        for (var i=0;i<hoss.length;i++) {
                            if (idd == hoss[i].id) {
                                flag =true;
                            }
                        }
                        if(flag){
                            hosGrid.selectRow(hosGrid.getRowIndex(id),true,true,true);
                        }
                    });
                }
            }
        },
        error:function (xhr, textStatus, statustText) {
            $func.alert("请求失败,状态:"+textStatus , "red");
        }
    });
}

//初始化选中关联医院
function searchHosSelected() {
    var alipayId = parent.oneAdminInfo.alipay_id;
    if (alipayId == null || alipayId == '') {
        $func.alert("获取支付宝账号信息失败，请重试！", "red");
        return;
    }
    var postData = "alipayId=" + alipayId;
    $.ajax({
        url: basePath+'managerAlipayUser/getHosByAlipayId',
        type: 'post',
        dataType: 'json',
        data:encodeURI(postData),
        success: function(back, textStatus, jqXHR) {
            if(!back){
                $func.alert("请求失败,状态:"+textStatus);
                return;
            }
            if(back.rowCount>0){
                selectedHosGrid.parse(back.gridr, "json");
                selectedHosGrid.setTotal(back.rowCount);
                selectedHosGrid.checkAll();
            }
        },
        error:function (xhr, textStatus, statustText) {
            $func.alert("请求失败,状态:"+textStatus , "red");
        }
    });
}

//医院列表点击事件(授权列表刷新增加或者减少相应医院)
function onSelectHosRow(rId) {
    var isExist = false;
    for (var j=0; j<arrayList.length; j++) {
        if (rId == arrayList[j]) {
            isExist = true;
            break;
        }
    }
    if (isExist) {
        return;
    } else {
        arrayList.push(rId);
    }
    // console.log(arrayList);
    for (var m=0; m<arrayList.length; m++) {
        hosGrid.selectRow(hosGrid.getRowIndex(arrayList[m]),true,true,true);
    }

    var hoss = getSelectedRows(hosGrid);
    // console.log(hos1.length+'a');
    // var hoss = getCheckedRowsByGrid(hosGrid, hosGrid.getColIndexById('select'));
    // console.log(hoss.length+'b');
    if (hoss == null || hoss.length == 0) {
        return;
    }
    selectedHosGrid.setTotal(0);
    selectedHosGrid.clearAll();
    var hosInfos = new Array();
    for (var i=0;i<hoss.length;i++) {
        var hosInfo = {};
        hosInfo.id = hoss[i].id;
        hosInfo.hos_name = hoss[i].hos_name;
        hosInfos.push(hosInfo);
    }
    $.ajax({
        url: basePath+'managerAlipayUser/refreshSelectGrid',
        type: 'post',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(hosInfos),
        success: function (back) {
            if(!back||!back.result){
                $func.alert(back.message?back.message:"获取列表失败", "red");
                return;
            }
            selectedHosGrid.parse(back.gridr, "json");
            selectedHosGrid.setTotal(back.rowCount);
            selectedHosGrid.checkAll();
        }
    });
}